﻿using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Routing;

namespace DH.Web.Filter
{
    public class AjaxRequestFilterAttribute: ActionMethodSelectorAttribute
    {
        public bool Ignore { get; set; }
        public AjaxRequestFilterAttribute(bool ignore = false)
        {
            Ignore = ignore;
        }
        public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
        {
            var res = false;
            var xKey = "X-Requested-With";
            var request = routeContext.HttpContext.Request;
            res= string.Equals(request.Query[xKey], "XMLHttpRequest", StringComparison.Ordinal) ||
                string.Equals(request.Headers[xKey], "XMLHttpRequest", StringComparison.Ordinal);

            return res;

            //var headkeys= routeContext.HttpContext.Request.Headers.Keys;
            //if (headkeys.Contains(xKey))
            //{
                
            //    var ajaxRequest = routeContext.HttpContext.Request.Headers[xKey];
            //    if (ajaxRequest.Count>0)
            //    {
            //        res = true;
            //    }
            //}
            //return res;
        }
    }
}
